package cn.com.controller.wxController;

import java.io.BufferedOutputStream; 
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.com.Enum.OrderStatus;
import cn.com.constant.Code;
import cn.com.db.model.Address;
import cn.com.db.model.DiyOrder;
import cn.com.db.model.Order;
import cn.com.db.model.WxDiyPayResult;
import cn.com.db.model.WxPayResult;
import cn.com.db.service.AddressService;
import cn.com.db.service.DiyOrderService;
import cn.com.db.service.OrderService;
import cn.com.db.service.WxDiyPayResultService;
import cn.com.db.service.WxPayResultService;
import cn.com.util.JsonUtil;
import cn.com.util.TimeUtil;
import cn.com.util.UidUtil;
import cn.com.util.XmlUtil;
import cn.com.wxUtil.PayUtil;
import cn.com.wxUtil.XMLUtil;
import cn.com.wxUtil.wxConstant;
import cn.com.wxUtil.refundUtil.WXUtil;
import cn.com.wxUtil.template.TemplateData;
import cn.com.wxUtil.template.WechatTemplate;

/**
 * 支付之后微信反馈信息回调控制器
 * 
 * @author mxq
 */
@RestController
@RequestMapping("/wx/")
public class PayOrderNotifyController {

	@Autowired
	OrderService orderService;
	@Autowired
	DiyOrderService diyOrderService;
	@Autowired
	WxPayResultService wxPayResultService;
	@Autowired
	WxDiyPayResultService wxDiyPayResultService;
	@Autowired
	AddressService addressService;

	@RequestMapping(value = "wxPayNotify/order")
	public void wxOrderNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 微信回调的xml通过流
		StringBuffer sb = new StringBuffer();
		InputStream inputStream = request.getInputStream();
		String s;
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		br.close();
		inputStream.close();
		// sb为微信返回的xml
		String notityXml = sb.toString();
		Map<String, String> m = XMLUtil.doXMLParse(notityXml);
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);
			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}
		// 写给微信的resultXML
		String resXml = "";
		if (WXUtil.isTenpaySign("UTF-8", packageParams, wxConstant.PAY_KEY)) {
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				/** 支付成功后业务逻辑代码start **/
				// JSONObject json = XmlUtil.xml2JSON(notityXml.getBytes());
				String wx_order_id = (String) packageParams.get("out_trade_no");
				// 创建微信支付结果,写入数据库
				WxPayResult wxPayResult = new WxPayResult();
				wxPayResult.setId(wx_order_id); // 商户订单号
				wxPayResult.setWx_pay_id((String) packageParams.get("transaction_id")); // 微信服务器生成的支付订单号
				String orders = wxPayResultService.getOrdersById(wx_order_id);
				List<String> orderIdList = UidUtil.splitStringByLine(orders);
				// 获得需要改变状态的订单
				List<Order> orderList = orderService.getOrderByIdList(orderIdList);
				String sellers = "", stores = "";
				for (Order order : orderList) {
					sellers += order.getSeller();
					sellers += "\\|";
					stores += order.getStore();
					stores += "\\|";
				}
				sellers = sellers.substring(0, sellers.length() - 1);
				stores = stores.substring(0, stores.length() - 1);
				wxPayResult.setWx_meta_info(notityXml);
				wxPayResult.setUser(orderList.get(0).getUser());
				wxPayResult.setSeller(sellers);
				wxPayResult.setStore(stores);
				wxPayResult.setUpdated_at(TimeUtil.getNowTimestamp());
				wxPayResult.setResult(wxConstant.SUCCESS); // 成功
				// 修改数据库微信结果表
				wxPayResultService.updateWxPayResult(wxPayResult);
				String time = ""; // 模板消息回显
				Timestamp updated_at = orderList.get(0).getUpdated_at();
				time = updated_at.toString();
				time = time.substring(0, time.indexOf("."));
				// 修改订单状态
				for (Order order : orderList) {
					orderService.updateOrderStatus(order.getId(), OrderStatus.WAIT_ORDERS.getStatus());
				}
				/****************** 测试版模板消息发送 *****************/
				try {
					// 1.获取access_token 成功!
					String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
							+ wxConstant.APPID + "&secret=" + wxConstant.SECRET;
					URL templateUrl = new URL(urls);
					String json = cn.com.util.HttpUtil.doGet(templateUrl);
					JSONObject jsonObject = JSON.parseObject(json);
					String access_token = (String) jsonObject.get("access_token");
					if (StringUtils.isEmpty(access_token)) {
						System.out.println(jsonObject.get("errmsg"));
					}
					// 2.调用模板消息发送接口
					urls = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="
							+ access_token;
					// 跳转页面
					String page = "/pages/order";
					String openid = (String) packageParams.get("openid");
					String fee = (String) packageParams.get("total_fee");
					BigDecimal total_fee = new BigDecimal(fee);
					total_fee = total_fee.movePointLeft(2);
					String prepay_id = wxPayResultService.getPrepayId(wx_order_id);
					String phone = orderList.get(0).getPhone();
					String userId = orderList.get(0).getUser();
					Address address = addressService.getUserDefAddress(userId);
					String userName = address.getName();
					String addressString = address.getProvince() + address.getCity() + address.getDistrict() + address.getDetail();
					// addressService.getUserDefAddress(userId)
					WechatTemplate w = new WechatTemplate();
					w.setTouser(openid);
					w.setForm_id(prepay_id);
					w.setTemplate_id(wxConstant.TEMPLATE_ID_PAY);
					w.setPage(page);
					LinkedHashMap<String,TemplateData> map = new LinkedHashMap<>();
					TemplateData t1 = new TemplateData();
					t1.setValue(time);
					t1.setColor("#000000");
					map.put("keyword1", t1);  //支付时间
					TemplateData t2 = new TemplateData();
					t2.setValue(total_fee+"元");
					t2.setColor("#000000");
					map.put("keyword2", t2);   // 支付金额
					TemplateData t3 = new TemplateData();
					t3.setValue(phone);
					t3.setColor("#000000");
					map.put("keyword3", t3);   // 联系人手机号
					TemplateData t4 = new TemplateData();
					t4.setValue(userName);
					t4.setColor("#000000");
					map.put("keyword4", t4);   // 联系人姓名
					TemplateData t5 = new TemplateData();
					t5.setValue(addressString);
					t5.setColor("#000000");
					map.put("keyword5", t5);   // 收货地址
					w.setData(map);
					String jsonTemplate = JSONObject.toJSON(w).toString();
					System.out.println(jsonTemplate);
					try {
						String postData = cn.com.wxUtil.HttpUtil.postData(urls, jsonTemplate);
						System.out.println(postData);
					} catch (Exception e) {
						System.out.println("发送模板消息失败");
					}
				} catch (Exception e) {
					System.out.println("发送模板消息异常");
				}
				/*******************************/
				/** 成功业务逻辑代码end **/

				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
				/** 失败业务逻辑 **/
				// 无
				/** 失败业务逻辑 **/
				// 返回给微信服务器的xml
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			}
		} else {
			/** 失败业务逻辑 **/
			// 无
			/** 失败业务逻辑 **/
			// 返回给微信服务器的xml
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		}
	}

	@RequestMapping(value = "wxPayNotify/diyOrder")
	public void wxDiyOrderNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 微信回调的xml通过流
		StringBuffer sb = new StringBuffer();
		InputStream inputStream = request.getInputStream();
		String s;
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = br.readLine()) != null) {
			sb.append(s);
		}
		br.close();
		inputStream.close();
		// sb为微信返回的xml
		String notityXml = sb.toString();
		Map<String, String> m = XMLUtil.doXMLParse(notityXml);
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		Iterator it = m.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = m.get(parameter);
			String v = "";
			if (null != parameterValue) {
				v = parameterValue.trim();
			}
			packageParams.put(parameter, v);
		}
		// 写给微信的resultXML
		String resXml = "";
		if (WXUtil.isTenpaySign("UTF-8", packageParams, wxConstant.PAY_KEY)) {
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				/** 支付成功后业务逻辑代码start **/
				String wx_order_id = (String) packageParams.get("out_trade_no");
				// 创建微信支付结果,写入数据库
				WxDiyPayResult wxDiyPayResult = new WxDiyPayResult();
				wxDiyPayResult.setId(wx_order_id); // 商户订单号
				wxDiyPayResult.setWx_pay_id((String) packageParams.get("transaction_id")); // 微信服务器生成的支付订单号
				String orders = wxDiyPayResultService.getOrdersById(wx_order_id);
				List<String> orderIdList = UidUtil.splitStringByLine(orders);
				// 获得需要改变状态的订单
				List<DiyOrder> diyOrders = diyOrderService.getDiyOrders(orderIdList);
				String sellers = "", stores = "";
				for (DiyOrder diyOrder : diyOrders) {
					sellers += diyOrder.getSeller();
					sellers += "\\|";
					stores += diyOrder.getStore();
					stores += "\\|";
				}
				sellers = sellers.substring(0, sellers.length() - 1);
				stores = stores.substring(0, stores.length() - 1);
				wxDiyPayResult.setWx_meta_info(notityXml);
				wxDiyPayResult.setUser(diyOrders.get(0).getUser());
				wxDiyPayResult.setSeller(sellers);
				wxDiyPayResult.setStore(stores);
				wxDiyPayResult.setUpdated_at(TimeUtil.getNowTimestamp());
				wxDiyPayResult.setResult(wxConstant.SUCCESS); // 成功
				// 修改数据库微信结果表
				wxDiyPayResultService.updateWxDiyPayResult(wxDiyPayResult);
				String time = ""; // 模板消息回显
				Timestamp updated_at = diyOrders.get(0).getUpdated_at();
				time = updated_at.toString();
				time = time.substring(0, time.indexOf("."));
				// 修改订单状态
				for (DiyOrder order : diyOrders) {
					diyOrderService.updateDiyOrderStatus(order.getId(), OrderStatus.WAIT_ORDERS.getStatus());
				}
				
				/****************** 测试版模板消息发送 *****************/
				try {
					// 1.获取access_token 成功!
					String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
							+ wxConstant.APPID + "&secret=" + wxConstant.SECRET;
					URL templateUrl = new URL(urls);
					String json = cn.com.util.HttpUtil.doGet(templateUrl);
					JSONObject jsonObject = JSON.parseObject(json);
					String access_token = (String) jsonObject.get("access_token");
					if (StringUtils.isEmpty(access_token)) {
						System.out.println(jsonObject.get("errmsg"));
					}
					// 2.调用模板消息发送接口
					urls = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="
							+ access_token;
					// 跳转页面
					String page = "/pages/my";
					String openid = (String) packageParams.get("openid");
					String fee = (String) packageParams.get("total_fee");
					BigDecimal total_fee = new BigDecimal(fee);
					total_fee = total_fee.movePointLeft(2);
					String prepay_id = wxDiyPayResultService.getPrepayId(wx_order_id);
					String phone = diyOrders.get(0).getPhone();
					String userId = diyOrders.get(0).getUser();
					Address address = addressService.getUserDefAddress(userId);
					String userName = address.getName();
					String addressString = address.getProvince() + address.getCity() + address.getDistrict() + address.getDetail();
					// addressService.getUserDefAddress(userId)
					WechatTemplate w = new WechatTemplate();
					w.setTouser(openid);
					w.setForm_id(prepay_id);
					w.setTemplate_id(wxConstant.TEMPLATE_ID_PAY);
					w.setPage(page);
					LinkedHashMap<String,TemplateData> map = new LinkedHashMap<>();
					TemplateData t1 = new TemplateData();
					t1.setValue(time);
					t1.setColor("#000000");
					map.put("keyword1", t1);
					TemplateData t2 = new TemplateData();
					t2.setValue(total_fee+"元");
					t2.setColor("#000000");
					map.put("keyword2", t2);
					TemplateData t3 = new TemplateData();
					t3.setValue(phone);
					t3.setColor("#000000");
					map.put("keyword3", t3);
					TemplateData t4 = new TemplateData();
					t4.setValue(userName);
					t4.setColor("#000000");
					map.put("keyword4", t4);
					TemplateData t5 = new TemplateData();
					t5.setValue(addressString);
					t5.setColor("#000000");
					map.put("keyword5", t5);
					w.setData(map);
					String jsonTemplate = JSONObject.toJSON(w).toString();
					System.out.println(jsonTemplate);
					try {
						String postData = cn.com.wxUtil.HttpUtil.postData(urls, jsonTemplate);
						System.out.println(postData);
					} catch (Exception e) {
						System.out.println("发送模板消息失败");
					}
				} catch (Exception e) {
					System.out.println("发送模板消息异常");
				}
				/*******************************/
				
				/** 成功业务逻辑代码end **/

				resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
						+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} else {
				/** 失败业务逻辑 **/
				// 无
				/** 失败业务逻辑 **/
				// 返回给微信服务器的xml
				resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
						+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			}
		} else {
			/** 失败业务逻辑 **/
			// 无
			/** 失败业务逻辑 **/
			// 返回给微信服务器的xml
			resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
					+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		}
	}

}
